package com.hht.baselibs.dialog

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel


/**
 * Author:chen'hu
 * Time:2024/5/8 17:17
 * Description:This is BaseDialog
 */
abstract class BaseFragmentDialog : DialogFragment(), CoroutineScope by MainScope() {
    private lateinit var rootView: View
    private var mWidth = 0
    private var mHeight = 0
    private var mOutCancel = true //点击外部取消
    lateinit var currentActivity: FragmentActivity


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        currentActivity = requireActivity()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        rootView = inflater.inflate(getResLayout(), container, false)
        initView(rootView)
        return rootView
    }

    abstract fun getResLayout(): Int

    abstract fun initView(rootView: View)


    override fun onStart() {
        super.onStart()
        initWindow()
    }

    private fun initWindow() {

        dialog?.apply {
            val window = this.window
            window?.apply {
                val params: WindowManager.LayoutParams = this.attributes
                if (mWidth == 0) {
                    params.width = ViewGroup.LayoutParams.WRAP_CONTENT
                } else {
                    params.width = mWidth
                }
                //设置高度
                if (mHeight == 0) {
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT
                } else {
                    params.height = mHeight
                }
                this.attributes = params
                // 设置对话框的背景
                this.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            }
        }
        isCancelable = mOutCancel
    }

    override fun getTheme(): Int {
        return android.R.style.Theme_Light_NoTitleBar_Fullscreen
    }

    fun setDialogWidth(width: Int) {
        mWidth = width
    }

    fun setDialogHeight(height: Int) {
        mHeight = height
    }

    fun setOutCancel(cancel:Boolean){
        mOutCancel=cancel
    }

    fun showDialog(
        manager: FragmentManager,
        tag: String = "UsbDialog",
    ): DialogFragment {
        val ft: FragmentTransaction = manager.beginTransaction()
        val fragmentByTag: Fragment? = manager.findFragmentByTag(tag)
        if (fragmentByTag != null) {
            //防止过快点击重复弹出报错
            if (fragmentByTag.isAdded) return this
            ft.show(fragmentByTag)
        } else {
            showAllowingLoss(manager, tag)
        }
        return this
    }

    /**
     * 解决 Can not perform this action after onSaveInstanceState问题
     * @param manager FragmentManager
     * @param tag     tag
     */
    private fun showAllowingLoss(manager: FragmentManager, tag: String?) {
        try {
            val cls: Class<*> = DialogFragment::class.java
            val mDismissed = cls.getDeclaredField("mDismissed")
            mDismissed.isAccessible = true
            mDismissed[this] = false
            val mShownByMe = cls.getDeclaredField("mShownByMe")
            mShownByMe.isAccessible = true
            mShownByMe[this] = true
        } catch (e: Exception) {
            //调系统的show()方法
            show(manager, tag)
            return
        }
        val ft = manager.beginTransaction()
        ft.add(this, tag)
        ft.commitAllowingStateLoss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        cancel()
    }
}